"""
配置文件
"""
import os
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()


class Config:
    """基础配置"""
    # Flask
    SECRET_KEY = os.getenv('SECRET_KEY', 'dev-secret-key-change-in-production')
    DEBUG = os.getenv('FLASK_DEBUG', 'False') == 'True'
    
    # Database
    DB_HOST = os.getenv('DB_HOST', '139.159.216.67')
    DB_PORT = os.getenv('DB_PORT', '33062')
    DB_USER = os.getenv('DB_USER', 'wohurpa')
    DB_PASSWORD = os.getenv('DB_PASSWORD', 'wohurpa@2002')
    DB_NAME = os.getenv('DB_NAME', 'minxiao')
    # Timeout & pool settings (可通过环境变量覆盖)
    DB_CONNECT_TIMEOUT = int(os.getenv('DB_CONNECT_TIMEOUT', '10'))  # MySQL 连接超时秒数
    DB_POOL_RECYCLE = int(os.getenv('DB_POOL_RECYCLE', '1800'))      # 回收连接秒数，防止 MySQL wait_timeout 导致的断开
    DB_POOL_TIMEOUT = int(os.getenv('DB_POOL_TIMEOUT', '30'))        # 等待获取连接的最大秒数
    
    SQLALCHEMY_DATABASE_URI = (
        f"mysql+pymysql://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
        "?charset=utf8mb4"
    )
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    # 关闭默认的 SQL 输出；如需临时开启，可设置环境变量 SQL_ECHO=True
    SQLALCHEMY_ECHO = os.getenv('SQL_ECHO', 'False') == 'True'
    # Engine 选项: 统一集中，避免在应用工厂里硬编码
    SQLALCHEMY_ENGINE_OPTIONS = {
        'pool_recycle': DB_POOL_RECYCLE,
        'pool_pre_ping': True,  # 失效连接自动检测
        'pool_timeout': DB_POOL_TIMEOUT,
        'connect_args': {
            'connect_timeout': DB_CONNECT_TIMEOUT
        }
    }
    
    # Flowable
    FLOWABLE_REST_URL = os.getenv('FLOWABLE_REST_URL', 'http://localhost:8080/flowable-rest')
    FLOWABLE_REST_USER = os.getenv('FLOWABLE_REST_USER', 'rest-admin')
    FLOWABLE_REST_PASSWORD = os.getenv('FLOWABLE_REST_PASSWORD', 'test')
    
    # Server
    SERVER_HOST = os.getenv('SERVER_HOST', '0.0.0.0')
    SERVER_PORT = int(os.getenv('SERVER_PORT', '17000'))
    SERVICE_HOST = os.getenv('SERVICE_HOST', f'http://localhost:{SERVER_PORT}')


class DevelopmentConfig(Config):
    """开发环境配置"""
    DEBUG = True
    # 保持与基类一致（通过 env 控制），不强制开启回显，避免日志噪音
    SQLALCHEMY_ECHO = Config.SQLALCHEMY_ECHO


class ProductionConfig(Config):
    """生产环境配置"""
    DEBUG = False
    SQLALCHEMY_ECHO = False

class TestingConfig(Config):
    """测试环境配置"""
    DEBUG = False
    SQLALCHEMY_ECHO = False
    TESTING = True
    SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'


# 配置字典
config = {
    'development': DevelopmentConfig,
    'production': ProductionConfig,
    'testing': TestingConfig,
    'default': DevelopmentConfig
}
